using Microsoft.EntityFrameworkCore;
using MyHomeworkWebAPi.Models.ef;
using MyHomeworkWebAPi.Models.Request;
using MyHomeworkWebAPi.Models.response;

namespace MyHomeworkWebAPi.Services
{
    /// <summary>
    /// 评论服务实现类
    /// </summary>
    public class CommentServices : ICommentServices
    {
        private readonly SecondHandTradingPlatformContext _context;

        /// <summary>
        /// 构造函数，注入数据库上下文
        /// </summary>
        /// <param name="context">数据库上下文</param>
        public CommentServices(SecondHandTradingPlatformContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取所有评论
        /// </summary>
        public async Task<List<Comment>> GetAllAsync()
        {
            return await _context.Comments
                .Include(c => c.Product)
                .Include(c => c.ParentComment)
                .OrderByDescending(c => c.CreateTime)
                .ToListAsync();
        }

        /// <summary>
        /// 根据ID获取评论
        /// </summary>
        public async Task<Comment?> GetByIdAsync(Guid commentId)
        {
            return await _context.Comments
                .Include(c => c.Product)
                .Include(c => c.ParentComment)
                .FirstOrDefaultAsync(c => c.CommentId == commentId);
        }

        /// <summary>
        /// 创建评论
        /// </summary>
        public async Task<Comment> CreateAsync(CommentCreateRequest request)
        {
            // 验证父评论是否存在（如果提供了父评论ID）
            if (request.ParentCommentId.HasValue)
            {
                var parentComment = await _context.Comments.FindAsync(request.ParentCommentId.Value);
                if (parentComment == null)
                {
                    throw new Exception("父评论不存在");
                }
            }

            var comment = new Comment
            {
                CommentId = Guid.NewGuid(),
                UserId = request.UserId,
                ProductId = request.ProductId,
                Content = request.Content,
                CreateTime = DateTime.Now,
                ParentCommentId = request.ParentCommentId
            };

            await _context.Comments.AddAsync(comment);
            await _context.SaveChangesAsync();

            return await GetByIdAsync(comment.CommentId);
        }

        /// <summary>
        /// 删除评论
        /// </summary>
        public async Task DeleteAsync(Guid commentId)
        {
            var comment = await _context.Comments.FindAsync(commentId);
            if (comment == null)
            {
                throw new Exception("评论不存在");
            }

            // 检查是否有子评论
            var hasReplies = await _context.Comments.AnyAsync(c => c.ParentCommentId == commentId);
            if (hasReplies)
            {
                throw new Exception("该评论下有回复，无法删除");
            }

            _context.Comments.Remove(comment);
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 获取用户的评论列表
        /// </summary>
        public async Task<List<Comment>> GetByUserIdAsync(Guid userId)
        {
            return await _context.Comments
                .Include(c => c.Product)
                .Include(c => c.ParentComment)
                .Where(c => c.UserId == userId)
                .OrderByDescending(c => c.CreateTime)
                .ToListAsync();
        }

        /// <summary>
        /// 获取商品的评论列表
        /// </summary>
        public async Task<List<Comment>> GetByProductIdAsync(Guid productId)
        {
            return await _context.Comments
                .Include(c => c.Product)
                .Include(c => c.ParentComment)
                .Where(c => c.ProductId == productId && c.ParentCommentId == null) // 只获取顶级评论
                .OrderByDescending(c => c.CreateTime)
                .ToListAsync();
        }

        /// <summary>
        /// 获取评论的回复列表
        /// </summary>
        public async Task<List<Comment>> GetRepliesAsync(Guid commentId)
        {
            return await _context.Comments
                .Include(c => c.Product)
                .Include(c => c.ParentComment)
                .Where(c => c.ParentCommentId == commentId)
                .OrderBy(c => c.CreateTime)
                .ToListAsync();
        }

        /// <summary>
        /// 获取评论统计数据
        /// </summary>
        public async Task<CommentStatistics> GetStatisticsAsync()
        {
            var today = DateTime.Today;
            var yesterday = today.AddDays(-1);
            var lastWeek = today.AddDays(-7);

            // 获取今日评论数
            var todayComments = await _context.Comments
                .CountAsync(c => c.CreateTime.Date == today);

            // 获取昨日评论数
            var yesterdayComments = await _context.Comments
                .CountAsync(c => c.CreateTime.Date == yesterday);

            // 获取总评论数
            var totalComments = await _context.Comments.CountAsync();

            // 获取上周评论数
            var lastWeekComments = await _context.Comments
                .CountAsync(c => c.CreateTime.Date >= lastWeek && c.CreateTime.Date < today);

            // 计算评论趋势
            var commentsTrend = yesterdayComments == 0 ? 100 : 
                ((double)(todayComments - yesterdayComments) / yesterdayComments) * 100;

            // 计算总趋势
            var totalTrend = lastWeekComments == 0 ? 100 :
                ((double)(totalComments - lastWeekComments) / lastWeekComments) * 100;

            // 计算平均评分（这里假设所有评论都是5星，因为数据库中没有评分字段）
            var averageRating = 4.5;

            return new CommentStatistics
            {
                TodayComments = todayComments,
                CommentsTrend = commentsTrend,
                TotalComments = totalComments,
                TotalTrend = totalTrend,
                AverageRating = averageRating
            };
        }
    }
} 